import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import router from 'umi/router';
import moment from 'moment';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import { Button, Card, message } from 'antd';

import '@ant-design/compatible/assets/index.css';

import BasicInfoElem from './components/BasicInfoElem';
import ServiceSettingElem from './components/ServiceSettingElem';

interface SaveAndEditInfoProps extends FormComponentProps {
  dispatch: Dispatch;
  detailInfo: any;
  checkPerm: any;
  currentUser: any;
  location: { query: any };
}

interface SaveAndEditInfoState {
  formValues: any;
}

@connect(
  ({
    logisticsCenterSaveAndUpdate: { detailInfo },
    common: { checkPerm },
    user: { currentUser },
  }: any) => ({ detailInfo, checkPerm, currentUser }),
)
class SaveAndEditInfoElem extends Component<SaveAndEditInfoProps, SaveAndEditInfoState> {
  state: SaveAndEditInfoState = {
    formValues: {},
  };

  componentDidMount() {
    const {
      location: {
        query: { id, gardenId },
      },
    } = this.props;
    if (id && gardenId) {
      this.fetchDetailInfo(id);
      this.fetchAction('common/fetchSelectOrgList', { gardenId });
      this.verifyPermissions();
    }

    this.fetchAction('common/fetchGardenList');
    this.fetchAction('common/fetchTariffList');
    this.fetchAction('common/fetchPassword');
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const {
      location: {
        query: { id },
      },
    } = this.props;
    if (id && id !== prevProps.location.query.id) {
      this.fetchDetailInfo(id);
    }
  }

  componentWillUnmount() {
    this.fetchAction('clear');
    this.fetchAction('common/clear');
  }

  fetchDetailInfo = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisticsCenterSaveAndUpdate/fetch',
      payload: { id, loadUser: 1 },
    });
  };

  mergeValues = (values: any) => {
    const { formValues } = this.state;
    this.setState({
      formValues: {
        ...formValues,
        ...values,
      },
    });
  };

  verifyPermissions = () => {
    const Updateparams = {
      name: 'update',
      oper: 'update',
      resource: 'conf:logis_sending_oper_info',
    };
    this.fetchAction('common/fetchCheckPerm', Updateparams);
  };

  handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      const { longitude, latitude } = values;
      if (longitude.length > 16 || Number(longitude) < -180 || Number(longitude) > 180) {
        message.error('经度输入不正确');
        return;
      }
      if (latitude.length > 16 || Number(latitude) < -90 || Number(latitude) > 90) {
        message.error('纬度输入不正确');
        return;
      }

      const { formValues } = this.state;
      if (formValues.file === 1) {
        message.error('请选择图片');
        return;
      }
      if (formValues.file && formValues.file.size > 5120000) {
        message.error('图片文件过大，请重新选择');
        return;
      }

      const { serviceTime, reserveTime = [] } = values;
      const new_reserveTime = reserveTime.map(
        (item: any) => `${moment(item[0]).format('HH:mm:ss')}
          -${moment(item[1]).format('HH:mm:ss')}`,
      ).join(',');
      const new_serviceTime = `${moment(serviceTime[0]).format('HH:mm:ss')}
        -${moment(serviceTime[1]).format('HH:mm:ss')}`.replace(/\s/g, '');

      const params = {
        ...values,
        ...formValues,
        serviceTime: new_serviceTime,
        reserveTime: new_reserveTime,
        isShare: values.isShare ? Number(values.isShare) : 0,
        geocode: 111,
        gardenId: values.garden ? values.garden.key : '',
        gardenName: values.garden ? values.garden.label : '',
      };

      const { detailInfo } = this.props;
      if (detailInfo && detailInfo.id) params.id = detailInfo.id;
      delete params.file_img;
      delete params.garden;

      this.fetchAction('saveOrUpdate', params);
    });
  };

  fetchAction = (typeName: string, payload = {}) => {
    const type = typeName.indexOf('common') >= 0
      ? typeName : `logisticsCenterSaveAndUpdate/${typeName}`;

    const { dispatch } = this.props;
    dispatch({ type, payload });
  };

  render() {
    const {
      form, detailInfo, checkPerm, currentUser,
    } = this.props;

    let auth = 'other';
    if (currentUser.is_root) {
      auth = 'root';
    } else if (checkPerm.update) {
      auth = 'manager';
    }

    return (
      <Fragment>
        <PageHeader />

        <Form
          hideRequiredMark
          className="tableListForm"
          onSubmit={this.handleSubmit}
        >
          <BasicInfoElem
            forms={form}
            auth={auth}
            detailInfo={detailInfo}
            mergeValues={this.mergeValues.bind(this)}
          />
          <ServiceSettingElem
            forms={form}
            auth={auth}
            detailInfo={detailInfo}
          />

          <Card bordered={false}>
            <Button
              type="primary"
              htmlType="submit"
            >
              保存
            </Button>
            <Button
              ghost
              type="primary"
              className="marginL16"
              onClick={() => router.goBack()}
            >
              取消
            </Button>
          </Card>
        </Form>
      </Fragment>
    );
  }
}

export default Form.create<SaveAndEditInfoProps>()(SaveAndEditInfoElem);
